// pages/home/home.js
const utils = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginFlat: false,
    userInfo: "",
    signinFlat: false,
    flatTime: "",
    signinNum: 0,
    avatarUrl: '',
    webNum: 0,
    collectNum: 0
  },
  getSigninNum(user_id) {
    let that = this
    return new Promise((reslove, reject) => {
      wx.request({
        url: 'http://localhost:3000/user/signinNum',
        method: "POST",
        data: {
          user_id
        },
        success(data) {
          console.log(data.data.num)
          that.setData({
            signinNum: data.data.num
          })
          reslove({
            code: 200,
            msg: "获取成功"
          })
        }
      })
    })

  },
  getImg() {
    if (wx.getStorageSync('avatarUrl')) {
      this.setData({
        avatarUrl: wx.getStorageSync('avatarUrl')
      })
    }
  },
  // http://localhost:3000/user/searchSignin


  toastWeb() {
    let num = this.data.webNum
    if (this.data.loginFlat) {
      wx.showModal({
        content: `您已经阅读过${num}首诗,请继续加油`,
        confirmColor: "#FDB201",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }

  },
  toastCollect() {
    let num = this.data.collectNum
    if (this.data.loginFlat) {
      wx.showModal({
        content: `学海无涯,您已经收藏${num}首诗`,
        confirmColor: "#FDB201",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }

  },
  toastSignin() {
    let num = this.data.signinNum
    if (this.data.loginFlat) {
      wx.showModal({
        content: `您已经签到${num}天`,
        confirmColor: "#FDB201",
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }

  },
  searchSignin(user_id) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/user/searchSignin',
        method: "POST",
        data: {
          user_id
        },
        success(data) {
          let newDate = new Date(data.data.time).getTime()
          console.log(newDate)
          that.setData({
            flatTime: newDate
          })
          let newDate2 = new Date(wx.getStorageSync('signinTime')).getTime()
          let newDate3 = new Date().getTime()
          if (newDate2 - newDate > 86400000) {
            console.log(1122)
            that.setData({
              signinFlat: false
            })
          } else {
            console.log(2211)

            that.setData({
              signinFlat: true
            })
          }
          resolve({
            code: 200,
            msg: "获取成功"
          })
        }
      })
    })

  },
  getSignin(create_time, user_id) {
    console.log(create_time, user_id)
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/user/signin',
        method: "POST",
        data: {
          create_time,
          user_id,
        },
        success(data) {
          console.log(data.data)
          if (data.data.code == 200) {
            resolve({
              code: 200,
              msg: "签到成功"
            })
            wx.setStorageSync('signinFlat', true)
            wx.setStorageSync('signinTime', create_time)
          } else if (data.data.code == 201) {
            resolve({
              code: 201,
              msg: "请勿查询签到"
            })
            wx.setStorageSync('signinFlat', true)
            wx.setStorageSync('signinTime', create_time)
          }
        }
      })
    })
  },
  async changeSignin() {
    if (this.data.loginFlat) {
      let that = this
      let dt = utils.formatTime(new Date())
      // create_time: utils.formatTime(dt),
      await this.getSignin(dt, this.data.userInfo.openid)
      this.setData({
        signinFlat: true
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }
  },
  jumpCollect() {
    console.log(123)
    if (this.data.loginFlat) {
      wx.navigateTo({
        url: '../collect/collect',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }

  },
  // 查询用户收藏数量
  userCollectList(user_id) {
    let that = this
    return new Promise((reslove, reject) => {
      wx.request({
        url: 'http://localhost:3000/user/userCollectList',
        method: "POST",
        data: {
          user_id: user_id
        },
        success(data) {
          console.log(data.data.num)
          that.setData({
            collectNum: data.data.num
          })
          reslove({
            code: "获取用户收藏数量成功",
            code: 200
          })
        }
      })
    })

  },
  jumpWeb() {
    if (this.data.loginFlat) {
      wx.navigateTo({
        url: '../webList/webList',
      })
    } else {
      wx.showToast({
        title: '请先登录',
        icon: "error"
      })
    }

  },
  getLogin(nickName, avatarUrl, openid, create_time) {
    let that = this
    wx.showLoading({
      title: '加载中',
    })
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/user/login',
        method: "POST",
        data: {
          nickName,
          avatarUrl,
          id: openid,
          create_time
        },
        async success(data) {
          console.log(data.data.row2)
          let userInfo = data.data.row2 ? data.data.row2[0] : data.data.userInfo
          // if (data.data.row2) {
          //   userInfo = data.data.row2
          // } else {
          //   userInfo = data.data.userInfo
          // }
          console.log(userInfo, 456456)
          wx.setStorageSync('nickName', userInfo.nickName)
          wx.setStorageSync('avatarUrl', userInfo.avatarUrl)
          wx.setStorageSync('openid', userInfo.id)
          wx.setStorageSync('create_time', userInfo.create_time)
          await that.searchSignin(userInfo.id)
          await that.getSigninNum(userInfo.id)
          await that.userCollectList(userInfo.id)
          that.getWebList()

          await that.getSignin(userInfo.create_time, userInfo.id)
          that.getImg()
          wx.hideLoading()
          resolve({
            code: 200,
            msg: "获取成功"
          })

        }
      })
    })

  },
  async getUserInfoFunc(nickName, avatarUrl) {
    let that = this;
    wx.showLoading({
      title: '登录中...',
    })
    let dt = new Date()
    wx.cloud.callFunction({
      name: "user",
      data: {
        create_time: utils.formatTime(dt),
        nickName: nickName,
        avatarUrl
      },
      async success(content) {
        let {
          errMsg,
          result
        } = content;
        if (errMsg == "cloud.callFunction:ok") {
          if (result.code == 200) {
            let {
              userInfo: {
                nickName,
                avatarUrl,
                openid,
                create_time,
              }
            } = result
            await that.getLogin(nickName, avatarUrl, openid, create_time)
            // wx.setStorageSync('nickName', nickName)
            // wx.setStorageSync('avatarUrl', avatarUrl)
            // wx.setStorageSync('openid', openid)
            // wx.setStorageSync('create_time', create_time)
          }
        }

      },
      fail(err) {
        console.log("请求失败", err)
      }
    })
  },
  down() {
    console.log(123);
    wx.removeStorage({
      key: "nickName"
    })
    wx.removeStorage({
      key: "avatarUrl"
    })
    wx.removeStorage({
      key: "openid"
    })
    wx.removeStorage({
      key: "create_time"
    })
    wx.removeStorage({
      key: "signinTime"
    })
    wx.removeStorage({
      key: "signinFlat"
    })
    this.setData({
      loginFlat: false,
      signinFlat: '',
      signinNum: 0,
      webNum: 0,
      collectNum: 0,
      avatarUrl: '',
      userInfo: ""
    })
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    if (!this.data.loginFlat) {
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo,
            loginFlat: true
          })
          let {
            userInfo: {
              nickName,
              avatarUrl
            }
          } = res;
          this.getUserInfoFunc(nickName, avatarUrl);

        }
      })
      console.log(this.data.userInfo)
    } else {
      wx.showToast({
        title: '已登录',
      })
    }

  },
  getWebList() {
    let that = this
    wx.request({
      url: 'http://localhost:3000/user/userWebList',
      method: "post",
      data: {
        user_id: wx.getStorageSync('openid')
      },

      success(data) {
        console.log(data.data.row)
        data.data.row.map((item) => {
          item.poet = JSON.parse(item.poet)
          item.tags = JSON.parse(item.tags)
        })
        that.setData({
          webNum: data.data.row.length
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    if (wx.getStorageSync('nickName')) {
      console.log(123)
      this.setData({
        loginFlat: true,
        userInfo: {
          nickName: wx.getStorageSync('nickName'),
          avatarUrl: wx.getStorageSync('avatarUrl'),
          openid: wx.getStorageSync('openid'),
          create_time: wx.getStorageSync('create_time')
        }
      })
    }
    if (wx.getStorageSync('signinTime')) {

      wx.showLoading({
        title: '加载中',
      })
      await this.userCollectList(wx.getStorageSync('openid'))
      this.getSigninNum(wx.getStorageSync('openid'))
      await this.searchSignin(wx.getStorageSync('openid'))
      this.getImg()
      this.getWebList()
      wx.hideLoading()

    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})